package cn.whdream.juc;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class TestReadWriteLock {
	public static void main(String[] args) {
		Demo demo = new Demo();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				demo.setNum((int) (Math.random()*101));
			}
		},"write").start();
		for (int i = 0; i < 100; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					demo.getNum();
				}
			},"read"+i).start();
		}
	}
	private static class Demo  {
		private int num = 0;
		private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
		public void getNum() {
			readWriteLock.readLock().lock();
			System.out.println("Thread"+Thread.currentThread()+" num :"+this.num);
			readWriteLock.readLock().unlock();
		}
		public void setNum(int num) {
			readWriteLock.writeLock().lock();
			this.num = num;
			System.out.println("----"+num);
			readWriteLock.writeLock().unlock();
		}
		
	}
}
